<template>
  <div class="common-dialog">
    <el-dialog
      :title="dialogTitle"
      width="50%"
      :model-value="props.modelValue"
      @update:modelValue="closeDialog"
    >
      <el-form 
        label-width="100px" 
        class="dialog-form" 
        :model="formData"
        :disabled="isViewMode"
      >
        <el-form-item label="序号">
          <el-input 
            disabled 
            v-model="formData.id" 
            placeholder="系统生成"
          />
        </el-form-item>
        <el-form-item label="账号">
          <el-input 
            v-model="formData.userName" 
            placeholder="请输入账号"
            :disabled="isViewMode"
          />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input 
            v-model="formData.userNickname" 
            placeholder="请输入昵称"
            :disabled="isViewMode"
          />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input 
            v-model="formData.userRealname" 
            placeholder="请输入真实姓名"
            :disabled="isViewMode"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select 
            v-model="formData.userGender" 
            placeholder="请选择性别" 
            style="width: 240px"
            :disabled="isViewMode"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="formData.userBirthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生日"
            style="width: 100%"
            :disabled="isViewMode"
          />
        </el-form-item>
        <el-form-item label="创建时间" v-if="isViewMode">
          <el-input 
            v-model="formData.createTime" 
            disabled
          />
        </el-form-item>
        <el-form-item label="头像">
          <!-- <el-input 
            v-model="formData.userProfilePictureSrc" 
            placeholder="请输入头像链接"
            :disabled="isViewMode"
          /> -->
          <div v-if="formData.userProfilePictureSrc" class="avatar-preview">
            <el-image
              :src="formData.userProfilePictureSrc"
              style="height: 80px; width: 80px; margin-top: 10px"
              fit="cover"
            />
          </div>
        </el-form-item>
        <el-form-item v-if="!isViewMode">
          <el-button type="primary" @click="saveUser">保存</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
      <template #footer v-if="isViewMode">
        <span class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="js" setup>
import { ref, defineProps, defineEmits, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import instance from "@/utils/request";

const formData = ref({
  id: '',
  userName: '',
  userNickname: '',
  userRealname: '',
  userGender: '',
  userBirthday: '',
  userProfilePictureSrc: '',
  createTime: ''
});

// 接收父组件传递的值
const props = defineProps({
  modelValue: Boolean,
  // 接收表格数据
  newFormData: Object,
  // 操作类型: view(浏览), add(添加), edit(编辑)
  operationType: {
    type: String,
    default: 'add' // 默认为添加
  }
});

// 计算属性：是否为浏览模式
const isViewMode = computed(() => {
  return props.operationType === 'view';
});

// 计算属性：对话框标题
const dialogTitle = computed(() => {
  switch (props.operationType) {
    case 'view': return '用户信息';
    case 'add': return '添加用户';
    case 'edit': return '编辑用户';
    default: return '用户信息';
  }
});

// 定义向父组件发送的事件
const emit = defineEmits(["update:modelValue", "update"]);

watch(() => props.newFormData, (newValue) => {
  if (newValue && Object.keys(newValue).length > 0) {
    formData.value = { ...newValue };
  } else {
    // 添加新用户时清空表单
    formData.value = {
      id: '',
      userName: '',
      userNickname: '',
      userRealname: '',
      userGender: '',
      userBirthday: '',
      userProfilePictureSrc: '',
      createTime: ''
    };
  }
}, { immediate: true });

const saveUser = async() => {
  // 添加表单验证
  if (!formData.value.userName) {
    ElMessage.error("账号不能为空！");
    return;
  }
  
  if (!formData.value.userNickname) {
    ElMessage.error("昵称不能为空！");
    return;
  }
  
  if (!formData.value.userRealname) {
    ElMessage.error("真实姓名不能为空！");
    return;
  }
  
  try {
    let response;
    if (formData.value.id === undefined || formData.value.id === '') {
      // 添加用户
      response = await instance.post('/user/addUser', {
        userName: formData.value.userName,
        userNickname: formData.value.userNickname,
        userRealname: formData.value.userRealname,
        userGender: formData.value.userGender,
        userBirthday: formData.value.userBirthday,
        userProfilePictureSrc: formData.value.userProfilePictureSrc
      });
    } else {
      // 修改用户
      response = await instance.put('/user/updateUserInfo', {
        id: formData.value.id,
        userName: formData.value.userName,
        userNickname: formData.value.userNickname,
        userRealname: formData.value.userRealname,
        userGender: formData.value.userGender,
        userBirthday: formData.value.userBirthday,
        userProfilePictureSrc: formData.value.userProfilePictureSrc
      });
    }
    
    if (response.data.code === 200) {
      ElMessage.success(formData.value.id ? "用户信息更新成功！" : "用户添加成功！");
      emit("update", response.data);
    } else {
      ElMessage.error(response.data.msg || (formData.value.id ? "用户信息更新失败！" : "用户添加失败！"));
    }
  } catch (error) {
    console.error('操作用户信息时出错:', error);
    ElMessage.error("操作用户信息时发生错误: " + (error.response?.data?.message || error.message));
  }
};

// 关闭弹窗方法
const closeDialog = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped>
.dialog-form {
  padding-right: 20px;
}

.avatar-preview {
  margin-top: 10px;
}
</style>